package com.mobile.learning;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.mobile.learning.lib.CustomAdapter;
import com.mobile.learning.lib.DBClass;
import com.mobile.learning.lib.FileHelper;
import com.mobile.learning.lib.Jenis;
import com.mobile.learning.lib.ServiceHelper;
import com.mobile.learning.lib.Soal;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.PopupMenu;
import android.widget.Toast;
import android.widget.PopupMenu.OnMenuItemClickListener;

public class TryoutListActivity extends ListActivity {
	DBClass db = new DBClass(this);
	public ListAdapter adapter;
	public List<Jenis> dataList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if (db.isLogin()) {

			setContentView(R.layout.activity_tryout);

			ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar_post);
			actionBar.setTitle("Tryout");

			actionBar.setHomeAction(new IntentAction(this, MainMenuActivity
					.createIntent(this), R.drawable.ic_action_back));

			if (Build.VERSION.SDK_INT >= 11)
				actionBar.addAction(new MenuAction());
			ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			dataList = db.getAllJenis("Tryout");
			for (Jenis j : dataList) {
				Soal s = db.getJumlahSoal(j.getId_jenis());
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("nama_jenis", j.getNama_jenis());
				map.put("kode_soal", j.getKode_jenis());
				map.put("versi_soal", j.getVersi_soal());
				map.put("jml_soal", s.getJml_soal());
				list.add(map);
			}
			Log.d("data", list.toString());
			adapter = new CustomAdapter(this, list,
					R.layout.activity_soal_list, new String[] { "nama_jenis",
							"kode_soal", "versi_soal", "jml_soal" }, new int[] {
							R.id.nama_soal, R.id.kode_soal, R.id.versi_soal,  R.id.jml_soal });

			setListAdapter(adapter);
			registerForContextMenu(getListView());

		} else {
			setContentView(R.layout.activity_tryout);
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					this);
			alertDialogBuilder.setTitle("Akses Ditolak !");
			alertDialogBuilder
					.setMessage(
							"Silahkan Login untuk Mengerjakan Soal Tryout !")
					.setCancelable(false)
					.setIcon(R.drawable.ic_icon_lock)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									TryoutListActivity.this.finish();
								}
							});
			AlertDialog alertDialog = alertDialogBuilder.create();
			alertDialog.show();
		}

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		menu.setHeaderTitle("Pilihan");
		menu.add(Menu.NONE, 0, Menu.NONE, "Kerjakan Soal");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		int pos = info.position;
		Jenis j = dataList.get(pos);
		Intent i = new Intent(TryoutListActivity.this, TryoutSoalActivity.class);
		switch (item.getItemId()) {
		case 0:
			i.putExtra("no_soal", 0);
			i.putExtra("jenis", j.getId_jenis());
			i.putExtra("index_soal", "0");
			i.putExtra("eTime", 0);
			i.putExtra("score", 0);
			startActivity(i);
			this.finish();
			return true;
		}
		return super.onContextItemSelected(item);
	}

	private class MenuAction extends AbstractAction {

		public MenuAction() {
			super(R.drawable.ic_action_overflow);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void performAction(View view) {
			// TODO Auto-generated method stub
			PopupMenu popup = new PopupMenu(getApplicationContext(), view);
			MenuInflater inflater = popup.getMenuInflater();
			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					// TODO Auto-generated method stub
					switch (item.getItemId()) {
					case R.id.refresh:
						new UpdateTask().execute();
						return true;
					case R.id.delete:
						db.deleteJenis();
						db.deleteSoal();
						db.deleteJawaban();
						Toast.makeText(TryoutListActivity.this,
								"Data Berhasil Dihapus", Toast.LENGTH_LONG)
								.show();
						onRestart();
						return true;
					default:
						return false;
					}

				}
			});
			inflater.inflate(R.menu.activity_latihan, popup.getMenu());
			popup.show();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.refresh:
			new UpdateTask().execute();
			return true;
		case R.id.delete:
			FileHelper fh = new FileHelper();
			fh.deleteData();
			db.deleteJenis();
			db.deleteSoal();
			db.deleteJawaban();
			Toast.makeText(TryoutListActivity.this, "Data Berhasil Dihapus",
					Toast.LENGTH_LONG).show();
			onRestart();
			return true;
		default:
			return false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_latihan, menu);
		return true;
	}

	// Update Task
	private class UpdateTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog = new ProgressDialog(
				TryoutListActivity.this);

		protected void onPreExecute() {
			dialog.setMessage("Loading....");
			dialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			dialog.dismiss();
			if (result == true) {
				Toast.makeText(TryoutListActivity.this, "Update Sukses",
						Toast.LENGTH_LONG).show();
				finish();

			} else {
				Toast.makeText(TryoutListActivity.this, "Update Failed",
						Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			ServiceHelper srv = new ServiceHelper();
			if (srv.UpdateTask(TryoutListActivity.this, "Tryout")) {
				return true;
			} else {
				return false;
			}
		}

	}

	protected void onRestart() {
		super.onRestart();
		startActivity(getIntent());
		finish();

	}

}
